﻿using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Microhard.Framework;
using Microhard.Permission;
using Microhard.Permission.Models;
using Microhard.Permission.Interface;
using Microsoft.Practices.Unity;
using FluentValidation.Mvc;
using Microhard.Framework.MVCHelper;
using Microhard.Core.Configuration;
using Microhard.Permission.MVCFilter;
using Microhard.WebUI.Models;
using Microhard.Framework.Extensions;
using Microhard.Core;
using Microhard.Permission.MVCFilter.MVCFilter;
using Micrhard.FMCG.Server.Interface;
using Microhard.Permission_MembershipImpl;


namespace Microhard.WebUI.Controllers
{
    public class AccountController : Controller
    {
        [Dependency]
        public IUser user { set; get; }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <returns></returns>
        public ActionResult Login()
        {
            return View();

        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Login([CustomizeValidator(RuleSet = "Login")]Logon model)
        {
            //做手机端判断
            bool isMobile = this.HttpContext.IsSuitableMobile() || this.HttpContext.IsWeixinClientRequest();

            if (ModelState.IsValid)
            {
                if (user.ValidatUser(model.UserName, model.Password))
                {
                    user.SignIn(model.UserName, false);

                    //是管理员
                    if (user.IsAdmin(model.UserName))
                    {
                        return RedirectToAction("Index", "User", new { area = "Admin" });
                    }
                    else
                    {

                        //表示帐号要验证员工信息
                        IUser iusre = IoC.Resolve<IUser>();
                        var theUser = iusre.GetUserByName(model.UserName);
                        if (theUser.AccountMappingEmployee)
                        {
                            IEmployee emp = IoC.Resolve<IEmployee>();
                            if (!emp.IsValidUser(theUser.UserName))
                            {
                                ModelState.AddModelError("", "此用户没有员工信息，无法登陆，请联系系统管理员");
                                return View(model);
                            }
                            else
                            {
                                return RedirectToAction("Welcome", "Account");
                            }
                        }
                        return RedirectToAction("Welcome", "Account");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }
            return View(model);
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult LogOff()
        {
            user.SignOut();
            this.HttpContext.Session.Clear();
            return RedirectToAction("Login");
        }

        /// <summary>
        /// 管理员欢迎
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForLogon()]
        public ActionResult Welcome()
        {
            return View();
        }

        /// <summary>
        /// 微信用户帐户绑定
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForWeixinMP]
        public ActionResult UserAccountBindingWXOpenID()
        {
            return View();
        }

        /// <summary>
        /// 微信用户帐户绑定成功
        /// </summary>
        /// <returns></returns>
        [MVCFilterAtrForWeixinMP]
        public ActionResult BindingAccountSucceed()
        {
            return View();
        }

        /// <summary>
        /// 微信用户帐户绑定操作
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="pwd"></param>
        /// <param name="weixinOpenID"></param>
        /// <returns></returns>
        [HttpPost]
        [MVCFilterAtrForWeixinMP]
        public ActionResult SaveUserAccountBindingWXOpenID([CustomizeValidator(RuleSet = "Login")]Logon model)
        {
            if (ModelState.IsValid)
            {
                IWeiXinAccount iwx = IoC.Resolve<IWeiXinAccount>();
                var result = iwx.BindingWeixinAccount(model.WeixinName, model.UserName, model.Password);
                if (result.IsSucceed)
                {
                    return RedirectToAction("BindingAccountSucceed", new { WeixinToken = model.WeixinToken, WeixinName = model.WeixinName });
                }
                ModelState.AddModelError("", result.ErrorMsgTxt);
            }
            return View("UserAccountBindingWXOpenID", model);
        }

        [MVCFilterAtrForLogon]
        public ActionResult MyProfile()
        {
            IEmployee iemp = IoC.Resolve<IEmployee>();
            var empModel = iemp.GetByUserName(this.GetCurrentUserName());
            if (empModel == null)
            {
                return RedirectToAction("Welcome");
            }
            return View(empModel);
        }

        [MVCFilterAtrForWeixinMP]
        [MVCFilterAtrForLogon]
        public ActionResult AutoLogon(string redirectUrl)
        {
            return View();
        }

        [HttpPost]
        [MVCFilterAtrForLogon]
        public ActionResult UpdatePassword(string oldPassword, string newPassword, string newPasswordCfm)
        {
            IEmployee iemp = IoC.Resolve<IEmployee>();
            var empModel = iemp.GetByUserName(this.GetCurrentUserName());
            if (string.IsNullOrEmpty(oldPassword) || string.IsNullOrEmpty(newPassword) || string.IsNullOrEmpty(newPasswordCfm))
            {
                ModelState.AddModelError("failed", "请输入密码");
                return View("MyProfile", empModel);
            }
            if (newPassword != newPasswordCfm)
            {
                ModelState.AddModelError("failed", "新密码两次输入不匹配，请重新输入");
                return View("MyProfile", empModel);
            }
            IUser user = IoC.Resolve<IUser>();
            if (!user.ChangePassword(this.GetCurrentUserName(), oldPassword, newPassword))
            {
                ModelState.AddModelError("failed", "修改密码失败");
                return View("MyProfile", empModel);
            }
            return this.LogOff();
        }

    }


}
